import Block from "./block";


import {distence, anim, watchValueChange, isTransparent, winH} from '../libs/utils.js';

export default class Scroller extends Block {
    constructor(x, y, width, height) {
        super(x, y, width, height);

        this.bindScrollEvent();
    }

    // 绑定滑动相关事件
    bindScrollEvent() {
        this._childStartPosition = null;
        this._childLastPosition = null;
        this.speed = 0; /// 当前滚动速度
        this.moveLastTime=0; ///上次滚动时间
        this.scrollTimer = null
        canvas.addEventListener('touchstart', this._triggerScrollerStart);
        canvas.addEventListener('touchmove', this._triggerScrollerMove);
        canvas.addEventListener('touchend', this._triggerScrollerEnd);
        canvas.addEventListener('touchcancel', this._triggerScrollerCancel);
    }
    removeClickEvent(){
        super.removeClickEvent()
        canvas.removeEventListener('touchstart', this._triggerScrollerStart);
        canvas.removeEventListener('touchmove', this._triggerScrollerMove);
        canvas.removeEventListener('touchend', this._triggerScrollerEnd);
        canvas.removeEventListener('touchcancel', this._triggerScrollerCancel);
    }
    _triggerScrollerStart = (e) => {
        // console.log(`触摸事件：touchstart`)
        if (this.disabled) return;
        this.speed = 0;
        if(this.scrollTimer !== null){
            clearTimeout(this.scrollTimer);
        }
        this.scrollTimer = null
        e = e.touches ? e.touches[0] : e;
        const { pageX: left, pageY: top } = e;
        var inner = this.checkIsOnThisSprite(left, top);
        if (!inner) return;

        let date = Date.now();
        this._childStartPosition = { left, top, time: +date, e };
        this._childLastPosition = { left, top, time: +date, e };
    }
    _triggerScrollerMove = (e) => {
        // console.log(`触摸事件：touchmove`)
        if (!this._childLastPosition) return;
        e = e.touches ? e.touches[0] : e;
        const { left, top } = this._childLastPosition;
        const dist = distence(left, top, e.pageX, e.pageY);

        if (dist < 5) return;  // 移动小于 5px 不算滑动
        let { y } = this.childSize;
        y += e.pageY - top;
        this.scrollTop(y, 0);
        let date = Date.now();
        if(this.moveLastTime ===0){
            this.moveLastTime = date;
        }else {
            let delTime = date - this.moveLastTime;
            this.moveLastTime = date;

            this.speed = (e.pageY-top)/delTime
            // console.log(`触摸事件：touchMove 当前滚动 差值 时间差： ${delTime}, 速度： ${this.speed}`)
        }
        this._childLastPosition = { left: e.pageX, top: e.pageY, time: +date, e };
    }
    _triggerScrollerEnd = () => {
        if (!this._childLastPosition) return;
        // console.log(`触摸事件：touchEnd 总共滚动距离 ${ this._childLastPosition.top - this._childStartPosition.top}`)
        console.log(`触摸事件：touchEnd 当前滚动速度 ${this.speed}`)

        if (this._childStartPosition.left === this._childLastPosition.left
        && this._childStartPosition.top === this._childLastPosition.top){
            return;
        }

        const { e, time } = this._childLastPosition || {};
        this._childStartPosition = null;


        const { y: min, height } = this;
        const { y, height: childHeight } = this.childSize;
        const max = min + height - childHeight;
        // console.log(`滑动结束-偏移位置, y: ${y}, min:${min}, max:${max} , y > min : ${(y > min)} , y < max: ${(y < max)}`);
        if (y > min) {
            console.log(`滑动结束-偏移位置1`);
            this.scrollTop(min, 300);
            this._childLastPosition = null;
        } else if (y < max) {
            console.log(`滑动结束-偏移位置2`);
            this.scrollTop(max, 300);
            this._childLastPosition = null;
        } else {
            // 弹性滑动还没开始搞
            if(Math.abs(this.speed) > 0.05){
                this._calculateSlide();
            }

            console.log(`滑动结束-偏移位置3`);
        }
    }

    /// 计算滑行
    _calculateSlide= () => {
        if(this.speed > 0.05){
            this.speed -=0.05;
        }else if(this.speed < -0.05){
            this.speed +=0.05;
        }else{
            this.speed = 0;
            if(this.scrollTimer !== null){
                clearTimeout(this.scrollTimer);
            }
            this._childLastPosition = null
            return;
        }

        if (!this._childLastPosition) return;
        const { left, top } = this._childLastPosition;

        let newTop = (top+ this.speed*30);

        let { y , height: childHeight} = this.childSize;
        y += newTop - top;



        const { y: min, height } = this;
        const max = min + height - childHeight;
        // console.log(`滑动结束-偏移位置, y: ${y}, min:${min}, max:${max} , y > min : ${(y > min)} , y < max: ${(y < max)}`);
        if (y > min) {
            console.log(`滑动结束-偏移位置1`);
            this.scrollTop(min, 300);
            this.speed = 0;
        } else if (y < max) {
            console.log(`滑动结束-偏移位置2`);
            this.scrollTop(max, 300);
            this.speed = 0;
        }else {
            console.log(`滑行了吗：${y} , ${top}, ${newTop} , 滚动速度${this.speed}`)
            this.scrollTop(y,30);
            let date = Date.now();
            this._childLastPosition = { left: left, top: newTop, time: +date };
        }
        this.scrollTimer = setTimeout(()=>{
            this._calculateSlide ()
        },30)
    }

    _triggerScrollerCancel= () => {
        // console.log(`触摸事件：touchCancel`)

        this._triggerScrollerEnd();
    }

    // ---------- 滑动至哪
    scrollTop(top, duration, easing) {
        const { y = 0 } = this.childSize;
        anim(y, top, duration, (now) => {
            const offset = now - this.childSize.y;
            // 子级整块远动
            this.childSize.y += offset;
            // 子级中的每块都运动
            this.child.forEach(item => {
                // console.log(`偏移位置 ${offset}`);
                item.y += offset;
            });
        });
    }
    scrollToBottom(){
        const { y: min, height } = this;
        const { y, height: childHeight } = this.childSize;
        const max = min + height - childHeight;
        this.scrollTop(max, 300);
    }

    /**
     * 从底部往上滚动的距离
     * @param pointY
     */
    scrollToPoint(pointY){
        // if(pointY < winH){
        //     pointY = winH
        // }
        const { y: min, height } = this;
        const { y, height: childHeight } = this.childSize;

        var scrollY = pointY- childHeight;


        ///  this.scrollTop(0, 300); 在最上面
        ///   this.scrollTop(winH-childHeight, 300); 滚动到最底部

        if(scrollY > 0 ){
            scrollY = 0;
        }
        if(scrollY < (winH-childHeight) ){
            scrollY = (winH-childHeight);
        }
        this.scrollTop(scrollY, 300);
    }
}